/**
 * This file is part of Wireless TransFer.
 *
 *   Wireless TransFer is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *	
 *   Wireless TransFer is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with Wireless TransFer.  If not, see <http://www.gnu.org/licenses/>.
 *
 *	 Copyright (C) 2011
 *   @author prebz
 */

package com.wirelesstransfer.activity.status;

import java.util.ArrayList;
import java.util.List;

import com.wirelesstransfer.R;
import com.wirelesstransfer.AsyncTasks.AsyncTaskElements;
import com.wirelesstransfer.AsyncTasks.UpdateStatusStatistics;
import com.wirelesstransfer.activity.dialogs.Question;
import com.wirelesstransfer.activity.filebrowser.FileSize;
import com.wirelesstransfer.client.ApacheClient;
import com.wirelesstransfer.server.ConnectedClients.ConnectedClient;
import com.wirelesstransfer.server.ConnectedClients.ConnectedClientsHandler;
import com.wirelesstransfer.server.WIFI.JettyServer;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class Status extends ListActivity implements OnClickListener {

	public static int SERVER = 0;
	public static int CLIENT = 1;
	
	private ArrayAdapter<String> arrayAdapter;
	
	private Intent intent;
	private Resources res;

	// Status TextFields for statistics values.
	private TextView uploadSpeedValue;
	private TextView downloadSpeedValue;
	private TextView totalUploadSizeValue;
	private TextView totalDownloadSizeValue;
	
	// Status TextFields for statistics units.
	private TextView uploadSpeedUnit;
	private TextView downloadSpeedUnit;
	private TextView totalUploadSizeUnit;
	private TextView totalDownloadSizeUnit;

	private TextView ip_txt;
	private TextView code_txt;
	private TextView ip_value_txt;
	private TextView code_value_txt;
		
	private List<String> adapterList;
	
	// Button
	private View sharedFilesButton;
	private View closeServer;
		
	private boolean serverUp;
	private boolean clientUp;
	private ApacheClient client;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.status); 
        
		res = getResources();

        // Initiate Status TextFields
        uploadSpeedValue = (TextView) findViewById(R.id.uploadspeedvalue_txt);
        downloadSpeedValue = (TextView) findViewById(R.id.downloadpeedvalue_txt);
        totalUploadSizeValue = (TextView) findViewById(R.id.totaluploadsizevalue_txt);
        totalDownloadSizeValue = (TextView) findViewById(R.id.totaldownloadsizevalue_txt);
        
        uploadSpeedValue.setText("N/A");
        downloadSpeedValue.setText("N/A");
        totalUploadSizeValue.setText(String.valueOf(0));
        totalDownloadSizeValue.setText(String.valueOf(0));

        uploadSpeedUnit = (TextView) findViewById(R.id.uploadspeedunit_txt);
    	downloadSpeedUnit = (TextView) findViewById(R.id.downloadspeedunit_txt);
    	totalUploadSizeUnit = (TextView) findViewById(R.id.totaluploadsizeunit_txt);
    	totalDownloadSizeUnit = (TextView) findViewById(R.id.totaldownloadsizeunit_txt);

    	// Standard is kB/s and Bytes.
    	uploadSpeedUnit.setText("kB/s");
    	downloadSpeedUnit.setText("kB/s");
    	totalUploadSizeUnit.setText(FileSize.BYTES);
    	totalDownloadSizeUnit.setText(FileSize.BYTES);

    	ip_txt = (TextView) findViewById(R.id.ip_txt);
    	code_txt = (TextView) findViewById(R.id.code_txt);
    	ip_value_txt = (TextView) findViewById(R.id.ip_value_txt);
    	code_value_txt = (TextView) findViewById(R.id.code_value_txt);
    	
		ip_value_txt.setText("Not");
		code_value_txt.setText("connected");
		
		AsyncTaskElements.ip_value_txt = this.ip_value_txt;
		AsyncTaskElements.code_value_txt = this.code_value_txt;
    	
        // Initiate sharedFiles button
        sharedFilesButton = findViewById(R.id.btn_sharedfiles);
        sharedFilesButton.setOnClickListener(this);
        closeServer = findViewById(R.id.btn_closeserver);
        closeServer.setOnClickListener(this);
        

        
		AsyncTaskElements.totalUploadSizeValue = this.totalUploadSizeValue;
		AsyncTaskElements.totalDownloadSizeValue = this.totalDownloadSizeValue;
		AsyncTaskElements.totalUploadSizeUnit = this.totalUploadSizeUnit;
		AsyncTaskElements.totalDownloadSizeUnit = this.totalDownloadSizeUnit;
		
		// TODO Start here and run with interval or move to ConnectedClient and ReceivedData and run when a file is finished?
        UpdateStatusStatistics s = new UpdateStatusStatistics();
		s.execute();
        
        // Add all connections.
		adapterList = new ArrayList<String>();
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		serverUp = JettyServer.getInstance().isRunning();
		client = ApacheClient.getInstance();
		clientUp = client.isActiveClient();
		
		adapterList.clear();
		
		if(serverUp) {
			setVisibleButton(true);

			for(ConnectedClient client : ConnectedClientsHandler.getInstance().getConnectedClients()){
				adapterList.add(client.getIP());
			}						

			
		} else if(clientUp) {
			setVisibleButton(false);

			// Files downloading.
			adapterList.add(client.getConnection().getIP());
		
		} else {
			setVisibleButton(false);
			// set some text "Not connected"

		}
				
		arrayAdapter = new CustomStatusArrayAdapter(this, adapterList);
		AsyncTaskElements.hosts = arrayAdapter;
		setListAdapter(arrayAdapter);	
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.questionmenu, menu);
        return true;
    }
	
	/**
	 * Handler for menu.
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.question_menu:
	    	intent = new Intent(this, Question.class);
	    	intent.putExtra(res.getString(R.string.question_TITLE),res.getString(R.string.question_status_title_txt));
	    	intent.putExtra(res.getString(R.string.question_TEXT),res.getString(R.string.question_status_txt));
	    	startActivity(intent);
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	/**
	 * onClickListener for the ListView
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		
		intent = new Intent(this, ClientStatus.class);
		if(serverUp){
			intent = intent.putExtra(res.getString(R.string.status_TITLE), adapterList.get(position) + ":" + SERVER);

		}
		else if(clientUp){
			intent.putExtra(res.getString(R.string.status_TITLE), adapterList.get(position) + ":" + CLIENT);

		}		
		startActivity(intent);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_sharedfiles:
			Intent question = new Intent(this, SharedFilesStatus.class);
			startActivity(question);
			break;
		case R.id.btn_closeserver:
			buildInitDialog(res.getString(R.string.send_dialog_init).toString()).show();
			break;
		}
		
	}
	
    /**
     * set the visibility of the sharedFiles button
     * @param visible true if visible
     */
    private void setVisibleButton(boolean visible){
            if(visible){
                    sharedFilesButton.setVisibility(View.VISIBLE);
                    ip_txt.setVisibility(View.VISIBLE);
                    code_txt.setVisibility(View.VISIBLE);
            		ip_value_txt.setVisibility(View.VISIBLE);
            		code_value_txt.setVisibility(View.VISIBLE);
            		closeServer.setVisibility(View.VISIBLE);
            }
            else{
                    sharedFilesButton.setVisibility(View.GONE);
                    ip_txt.setVisibility(View.GONE);
                    code_txt.setVisibility(View.GONE);
            		ip_value_txt.setVisibility(View.GONE);
            		code_value_txt.setVisibility(View.GONE);
            		closeServer.setVisibility(View.GONE);
            }
    }
    
	/**
	 * Creates text in a dialog with yes/no key
	 * @param action
	 * @return
	 */
	public AlertDialog buildInitDialog(String action){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(action)
		.setCancelable(false)
		.setPositiveButton(res.getString(R.string.send_dialog_yes), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				JettyServer.getInstance().stopServer();
onResume();			}
		})
		.setNegativeButton(res.getString(R.string.send_dialog_no), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
			}
		});
		AlertDialog alert = builder.create();
		return alert;
	}

}
